package org.openclinic.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;

import javax.annotation.PostConstruct;
import javax.validation.Valid;

import org.apache.commons.beanutils.BeanUtils;
import org.openclinic.domain.Clinic;
import org.openclinic.exception.AbstractExceptionHandler;
import org.openclinic.exception.DomainException;
import org.openclinic.to.AjaxResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;

@Controller
public class ClinicController extends AbstractExceptionHandler {
	
	@Autowired
	private Clinic clinic;

	@RequestMapping(value = "/clinic.do", method = RequestMethod.GET)
	public ModelAndView init() {	
		ModelAndView mav = new ModelAndView("clinic.view");
		mav.addObject("clinic", clinic);
		
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(value = "/clinic/save.action", method = RequestMethod.POST)
	public AjaxResponse save(@Valid @ModelAttribute Clinic clinic, BindingResult validationResult) {
		if(!validationResult.hasErrors()) {
			Gson gson = new Gson();
			try {
				BeanUtils.copyProperties(this.clinic, clinic);
	            FileWriter writer = new FileWriter(new File(System.getProperty("user.home"),"openclinic.json"));
	            writer.write(gson.toJson(this.clinic));
	            writer.close();
			} catch (Exception e) {
				// ignore
			}
			return AjaxResponse.SUCCESS;
		}
		throw new DomainException(validationResult.getAllErrors());
	}
		
	@PostConstruct
	public void setupClinicContactInfo() {
        Gson gson = new Gson();

        try {
	        BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(System.getProperty("user.home"),"openclinic.json")));
	        BeanUtils.copyProperties(this.clinic, gson.fromJson(bufferedReader, Clinic.class));
        } catch (FileNotFoundException e) {
			clinic.setAddress("Utilize o menu Cadastro para definir os dados de sua clínica");
			clinic.setPhone("-");
			clinic.setLatitude("-30.02986");
			clinic.setLongitude("-51.228728");
			clinic.setMorningStartTime("08:00");
			clinic.setMorningEndTime("12:00");
			clinic.setAfternoonStartTime("13:00");
			clinic.setAfternoonEndTime("18:00");
        } catch (Exception e) {
			// ignore
		}
	}
}
